<template>
  <div class="cancelClassStudent">
    <!-- 顶部操作栏 -->
    <div class="top-actions">
      <div class="filter-section">
        <van-field
          v-model="searchName"
          placeholder="搜索学生姓名"
          clearable
          class="search-field"
          @input="handleSearch"
        >
          <template #left-icon>
            <van-icon name="search" size="16" />
          </template>
        </van-field>
      </div>
    </div>

    <div class="assets_main">
      <van-list
        v-if="result.length"
        v-model="loading"
        :finished="finished"
        offset="30"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div
          class="item"
          v-for="(item, index) in result"
          :key="index"
        >
          <div class="item_wrap">
            <div class="item_wrap_detail">
              <div class="status-corner" :class="getStatusClass(item.marketingState)">{{ getStatusText(item.marketingState) }}</div>
              <div class="item_wrap_title">{{ item.studentName }}</div>
              <div style="display: flex;justify-content:space-between;">
                <div class="detail_title">年龄：{{ item.studentAge }}岁</div>
                <div class="detail_title">剩余课时：{{item.classSurplusTime}}课时</div>
              </div>
              <div class="ctr">
                <div class="btn" v-if="item.marketingState != '0' && item.marketingState != '2' && item.classSurplusTime > 0" @click="cancelClass(item)">销课</div>
                <div class="btn" v-if="item.marketingState != '0' && item.marketingState != '2' && item.classSurplusTime > 0" @click="applyLeave(item)">请假</div>
                <div class="btn" v-if="item.marketingState != '2' && item.classSurplusTime > 0"@click="tocommemt(item)">评价</div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
      <div class="nodata" v-else>
        <van-empty description="暂无数据哦" />
      </div>
    </div>

    <!-- 销课弹窗组件 -->
    <CancelClassDialog
      :visible="showCancelDialog"
      :student-info="currentStudent"
      :course-params="{
        courseStartime: params.courseStartime,
        counrseEndtime: params.counrseEndtime,
        teacherNumber: params.teacherNumber
      }"
      @confirm="handleCancelClassConfirm"
      @close="handleCancelClassClose"
      @update:visible="showCancelDialog = $event"
    />
  </div>
</template>

<script>
import { Empty, List, Dialog, Field, Icon } from 'vant';
import CancelClassDialog from '@/components/CancelClassDialog.vue';
const courseType = {
  excellentCourse: '2', // 精品课程
  publicCourse: '0', // 常规课程
  auditionCourse: '1', // 试听课程
}
export default {
  components: {
    [Empty.name]: Empty,
    [List.name]: List,
    [Dialog.Component.name]: Dialog.Component,
    [Field.name]: Field,
    [Icon.name]: Icon,
    CancelClassDialog,
  },
  data() {
    return {
      source: courseType.auditionCourse,
      current: 1,
      size: 10,
      loading: false,
      finished: true,
      result: [],
      originalResult: [], // 保存原始数据用于筛选
      params: {
        classId: '',
        courseStartime: '',
        counrseEndtime: '',
      },
      showCancelDialog: false,
      currentStudent: null,
      searchName: '', // 搜索学生姓名
    }
  },
  mounted() {
    console.log(this.$route.params, 'this.$route', this.$route)
    this.params.classId = this.$route.params.classId
    this.params.courseId = this.$route.params.courseNumber
    this.params.teacherNumber = this.$route.params.teacherNumber;
    this.params.courseStartime = this.$route.params.courseStartime
    this.params.counrseEndtime = this.$route.params.counrseEndtime
    this.getData()
  },
  methods: {
    onLoad() {
      console.log('load')
      this.current = this.current + 1;
      this.getData()
    },
    getData() {
      let params = {
        // current: this.current,
        // size: this.size
        classId: this.params.classId,
        courseId: this.params.courseId,
        courseStartime: this.params.courseStartime,
        counrseEndtime: this.params.counrseEndtime,
      }

      console.log("上送参数"+params.classId+"|"+params.courseId+"|"+params.courseStartime+"|"+params.counrseEndtime+"|")
      this.$http.getCancelStudentList(params).then((res) => {
        // let { records, current, pages } = res.data.result
        console.log(res)
        this.result = res.data.result;
        this.originalResult = [...res.data.result]; // 保存原始数据
        this.loading = true;
        this.finished = true
        //   this.result = current > 1 ? [...this.result].concat(records) : records
        //   if (current >= pages) {
        //     this.loading = true;
        //     this.finished = true
        //   }
        //   else {
        //     this.finished = false
        //     this.loading = false
        //   }
        })
        .catch((err) => {
          console.log(err, 'err')
          this.$toast(err.data.message)
        })
    },

    // 处理搜索
    handleSearch() {
      this.filterData();
    },

    // 筛选数据
    filterData() {
      let filteredData = [...this.originalResult];

      // 按姓名搜索
      if (this.searchName) {
        filteredData = filteredData.filter(item =>
          item.studentName && item.studentName.toLowerCase().includes(this.searchName.toLowerCase())
        );
      }

      this.result = filteredData;
    },
    cancelClass(item) {
      this.currentStudent = item;
      this.showCancelDialog = true;
    },

    handleCancelClassConfirm(cancelData) {
      const { xknumber, cancelReason } = cancelData;
      this.executeCancelClass(this.currentStudent, xknumber, cancelReason);
      this.showCancelDialog = false;
      this.currentStudent = null;
    },

    handleCancelClassClose() {
      this.showCancelDialog = false;
      this.currentStudent = null;
    },

    executeCancelClass(item, xknumber, cancelReason) {
      let query = {
        classSurplusTime: item.classSurplusTime,
        byclassid: item.id,
        courseStartime: this.params.courseStartime,
        counrseEndtime: this.params.counrseEndtime,
        courseId: item.courseId,
        classId: item.classId,
        state: '0',
        studentId: item.studentId,
        teacherNumber: this.params.teacherNumber,
        xknumber: xknumber,
        cancelReason: cancelReason || ''
      }

      this.$http.cancelStatusClass(query).then(res => {
        console.log(res, 'res消课')
        if(res.data.code == 200) {
          this.$toast(res.data.message);
          this.getData();
        }
      }).catch(err => { this.$toast('销课失败：'+err.data.message) })
    },

    tocommemt(item) {
        this.$router.push({name: 'comment', params: {...this.$route.params, item, teacherNumber: this.params.teacherNumber, courseNumber: this.params.courseId}})
    },

    applyLeave(item) {
      this.$dialog.confirm({
        title: '请假申请',
        message: `确定要为 ${item.studentName} 申请请假吗？`,
      })
      .then(() => {
        this.executeApplyLeave(item);
      })
      .catch(() => {
        // 取消操作
      });
    },

    executeApplyLeave(item) {
      let query = {
        classSurplusTime: item.classSurplusTime,
        byclassid: item.id,
        courseStartime: this.params.courseStartime,
        counrseEndtime: this.params.counrseEndtime,
        courseId: item.courseId,
        classId: item.classId,
        state: '2', // 请假状态
        studentId: item.studentId,
        teacherNumber: this.params.teacherNumber,
        xknumber: 0, // 销课数量为0
        cancelReason: ''
      }

      this.$http.cancelStatusClass(query).then(res => {
        console.log(res, 'res请假')
        if(res.data.code == 200) {
          this.$toast(res.data.message);
          this.getData();
        }
      }).catch(err => { this.$toast('请假申请失败：'+err.data.message) })
    },

    getStatusText(status) {
      if(status==null){
          status=3;
      }
      const statusMap = {
        '3': '正常',
        '2': '请假中',
        '0': '已销课'
      };
      return statusMap[status] || '未知状态';
    },

    getStatusClass(status) {
      if(status==null){
          status=3;
      }
      const statusClassMap = {
        '3': 'status-normal',
        '2': 'status-leave',
        '0': 'status-canceled'
      };
      return statusClassMap[status] || 'status-unknown';
    },
  },
}
</script>

<style lang="scss" scoped>
.cancelClassStudent {
  color: #333;
  height: 100%;
  background: #f5f5f5;

  /* 顶部操作栏样式 */
  .top-actions {
    background: #fff;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
    position: sticky;
    top: 0;
    z-index: 10;

    .filter-section {
      display: flex;
      align-items: center;
      gap: 12px;

      .search-field {
        flex: 1;
        border-radius: 8px;
        background: #f8f9fa;
        border: 1px solid #e9ecef;

        ::v-deep .van-field__control {
          font-size: 14px;
        }

        ::v-deep .van-field__left-icon {
          color: #6c757d;
        }
      }

    }
  }
  .assets_main {
    height: 100%;
    width: 100%;
    overflow: hidden;
    padding: 15px 0;
    .item:first-child {
      margin-top: 0;
    }
    .item {
      width: calc(100% - 30px);
      margin: 0 auto 15px;
      position: relative;
      padding: 16px;
      background: #fff;
      box-sizing: border-box;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.12);
        transform: translateY(-1px);
      }

      .item_wrap {
        display: flex;
        align-items: flex-start;
        .item_wrap_img {
          width: 70px;
          height: 70px;
        }
        .item_wrap_detail {
          flex: 1;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 100%;
          padding: 0 0 0 12px;
          box-sizing: border-box;
          position: relative;
          .item_wrap_title {
            width: 100%;
            min-height: 25px;
            font-weight: 700;
            text-align: left;
            font-size: 17px;
            color: #333;
            margin-bottom: 8px;
            line-height: 1.4;
          }

          .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            .detail_title {
              font-size: 14px;
              color: #666;
              line-height: 1.4;
            }
          }

          .status-corner {
            position: absolute;
            top: 0;
            right: 12px;
            display: inline-block;
            padding: 2px 8px;
            border-radius: 2px;
            font-size: 12px;
            font-weight: 500;
            z-index: 1;
            text-align: center;
            min-width: 50px;

            &.status-normal {
              background: #f6ffed;
              color: #52c41a;
            }

            &.status-leave {
              background: #fff7e6;
              color: #fa8c16;
            }

            &.status-canceled {
              background: #f6ffed;
              color: #389e0d;
            }

            &.status-evaluated {
              background: #f0f5ff;
              color: #1890ff;
            }

            &.status-unknown {
              background: #f5f5f5;
              color: #8c8c8c;
            }
          }


          .ctr {
            margin-top: 12px;
            border-top: 1px solid #f0f0f0;
            padding-top: 12px;
            box-sizing: border-box;
            display: flex;
            justify-content: flex-end;
            gap: 8px;

            .btn {
              border: 1px solid #d9d9d9;
              border-radius: 16px;
              padding: 6px 16px;
              color: #666;
              font-size: 13px;
              font-weight: 500;
              transition: all 0.2s ease;
              cursor: pointer;

              &:hover {
                background: #f5f5f5;
                border-color: #bfbfbf;
              }

              &:active {
                background: #e6e6e6;
                transform: scale(0.98);
              }

              &:first-child {
                margin-left: 0;
              }
            }
          }

          .detail_title {
            width: 100%;
            font-size: 14px;
            color: #666;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            line-height: 1.4;
          }
        }
      }
    }
    .nodata {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
<style lang="scss">
.cancelClassStudent {
  .van-list {
    height: 100%;
    overflow: scroll;
  }
  .van-tab {
    font-size: 16px;
  }
}
</style>
